<script setup lang="ts">
import {ref, computed, onMounted} from 'vue';
import {UserOutlined, TeamOutlined, SearchOutlined, SendOutlined} from '@ant-design/icons-vue';
import {useLoginUserStore} from "@/stores/useLoginUserStore.ts";
import {getChatRecord} from "@/api/chatController.ts";
import {useRoute} from "vue-router";
import {getUserById} from "@/api/userController.ts";
import {message} from "ant-design-vue";

// 类型定义
interface UserVO {
  id: string;
  username: string;
  userAvatar?: string;
  userProfile?: string;
  userTags?: string[];
  teach?: string[];
  learn?: string[];
}

interface TeamVO {
  id: string;
  teamname: string;
  description?: string;
  avatar?: string;
  tags?: string[];
  maxPerson?: number;
  userVO?: UserVO;
  memberVOs?: UserVO[];
}

interface ChatVO {
  fromId: string;
  toId?: string | null;
  text: string;
  chatType: number; // 1-私聊，2-群聊
  createTime: string;
  teamId?: string | null;
  isRead?: number;
}

interface ChatRecordVO {
  targetUserVO?: UserVO | null;
  targetTeamVO?: TeamVO | null;
  chatVO: ChatVO[];
}

const route = useRoute()
// 模拟当前登录用户
const loginUserStore = useLoginUserStore();
const currentUser = computed(() => (loginUserStore.loginUser));


// 静态聊天数据 - 直接使用用户提供的聊天记录示例
// const staticChatRecords: ChatRecordVO[] = [
//   {
//     targetUserVO: {
//       id: '2',
//       username: '无名2',
//       userAvatar: null,
//       userProfile: null,
//       userTags: ["qwq", "qaq"],
//       teach: ["音乐", "美术"],
//       learn: ["数学"],
//       userRole: "user",
//       status: 1,
//       points: 0,
//       blogCount: 0,
//       blogTotalView: "0",
//       likeCount: 0,
//       collectCount: 0,
//       followCount: 0,
//       fanCount: 0,
//       createTime: "2025-09-14T06:39:35.000+00:00",
//       updateTime: "2025-09-27T07:32:15.000+00:00"
//     },
//     targetTeamVO: null,
//     chatVO: [
//       {
//         fromId: '1',
//         toId: '2',
//         text: "哈哈",
//         chatType: 1,
//         createTime: "2025-10-05T08:19:18.000+00:00",
//         teamId: null,
//         isRead: 0
//       },
//       {
//         fromId: '1',
//         toId: '2',
//         text: "请问请问",
//         chatType: 1,
//         createTime: "2025-10-05T08:18:59.000+00:00",
//         teamId: null,
//         isRead: 0
//       },
//       {
//         fromId: '2',
//         toId: '1',
//         text: "哈哈",
//         chatType: 1,
//         createTime: "2025-10-01T09:00:43.000+00:00",
//         teamId: null,
//         isRead: 0
//       }
//     ]
//   },
//   {
//     targetUserVO: null,
//     targetTeamVO: {
//       id: '1',
//       teamname: "用户1的队伍",
//       description: "泥嚎呀",
//       avatar: null,
//       tags: [],
//       maxPerson: 10,
//       userVO: {
//         id: '1',
//         userAccount: "admin",
//         username: "管理员",
//         userAvatar: " https://cloud-picture-1361877603.cos.ap-guangzhou.myqcloud.com/public/1/2025-09-11_ze1A7F3vUcHALYrf.webp  ",
//         userProfile: "大家嚎",
//         userTags: ["qwq"],
//         teach: ["音乐", "美术"],
//         learn: ["六级", "雅思"],
//         userRole: "admin",
//         status: 1,
//         points: 123,
//         blogCount: 0,
//         blogTotalView: "0",
//         likeCount: 0,
//         collectCount: 0,
//         followCount: 1,
//         fanCount: 0,
//         createTime: "2025-09-14T05:06:39.000+00:00",
//         updateTime: "2025-09-27T07:32:15.000+00:00"
//       },
//       memberVOs: [
//         {
//           id: '1',
//           userAccount: "admin",
//           username: "管理员",
//           userAvatar: " https://cloud-picture-1361877603.cos.ap-guangzhou.myqcloud.com/public/1/2025-09-11_ze1A7F3vUcHALYrf.webp  ",
//           userProfile: "大家嚎",
//           userTags: ["qwq"],
//           teach: ["音乐", "美术"],
//           learn: ["六级", "雅思"],
//           userRole: "admin",
//           status: 1,
//           points: 123,
//           blogCount: 0,
//           blogTotalView: "0",
//           likeCount: 0,
//           collectCount: 0,
//           followCount: 1,
//           fanCount: 0,
//           createTime: "2025-09-14T05:06:39.000+00:00",
//           updateTime: "2025-09-27T07:32:15.000+00:00"
//         },
//         {
//           id: '2',
//           userAccount: "user2",
//           username: "无名2",
//           userAvatar: null,
//           userProfile: null,
//           userTags: ["qwq", "qaq"],
//           teach: ["音乐", "美术"],
//           learn: ["数学"],
//           userRole: "user",
//           status: 1,
//           points: 0,
//           blogCount: 0,
//           blogTotalView: "0",
//           likeCount: 0,
//           collectCount: 0,
//           followCount: 0,
//           fanCount: 0,
//           createTime: "2025-09-14T06:39:35.000+00:00",
//           updateTime: "2025-09-27T07:32:15.000+00:00"
//         }
//       ],
//       status: 0,
//       createTime: "2025-09-14T09:45:11.000+00:00",
//       updateTime: "2025-09-14T09:45:11.000+00:00"
//     },
//     chatVO: [
//       {
//         fromId: '1',
//         toId: null,
//         text: "qwq",
//         chatType: 2,
//         createTime: "2025-10-01T09:01:21.000+00:00",
//         teamId: '1',
//         isRead: 0
//       },
//       {
//         fromId: '2',
//         toId: null,
//         text: "俄",
//         chatType: 2,
//         createTime: "2025-10-01T09:01:13.000+00:00",
//         teamId: '1',
//         isRead: 0
//       }
//     ]
//   }
// ];

// 聊天数据状态
const chatRecords = ref<ChatRecordVO[]>();
const currentChat = ref<ChatRecordVO | null>(null);
const newMessage = ref('');

// 选择聊天对象
const selectChat = (contact: ChatRecordVO) => {
  currentChat.value = contact;
  setTimeout(() => {
    scrollToBottom();
  }, 100);
};

// 滚动到底部
const scrollToBottom = () => {
  const chatContainer = document.querySelector('.chat-messages');
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }
};

// 格式化时间为年月日时分秒
const formatTime = (timeString: string) => {
  const date = new Date(timeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取默认头像
const getDefaultAvatar = () => {
  return 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png ';
};

// 获取联系人头像
const getContactAvatar = (userId: string) => {
  // 根据userId查找对应的用户头像
  for (const contact of chatRecords.value) {
    if (contact.targetUserVO?.id === userId) {
      return contact.targetUserVO.userAvatar || getDefaultAvatar();
    }
    if (contact.targetTeamVO?.memberVOs) {
      const member = contact.targetTeamVO.memberVOs.find(m => m.id === userId);
      if (member) {
        return member.userAvatar || getDefaultAvatar();
      }
    }
  }
  return getDefaultAvatar();
};

//获取聊天记录
const fetchChatRecords = async () => {
  try {
    const res = await getChatRecord({
      id: currentUser.value.id
    });
    if (res.data.code === 0 && res.data.data) {
      chatRecords.value = res.data.data;
    } else {
      console.error("获取聊天记录失败", res.data.message);
    }
  } catch (error) {
    console.error("获取聊天记录异常", error);
  }
}


//页面初始化
const InitPage = async () => {
  //获取路径上的 id
  const routeId = route.query.id;      // "1" (字符串类型)
  const routeType = route.query.type;  // "user" (字符串类型)
  if (routeId) {

    //从聊天记录中查找是否有该用户的聊天记录
    const chatRecord = chatRecords.value.find(record => (routeType === "user" && record.targetUserVO?.id == routeId) || (routeType === "team" && record.targetTeamVO?.id == routeId));
    if (chatRecord) {
      //选择这一个，并滚动到底部
      selectChat(chatRecord);
      console.log("禁了")

      return
    } else {
      //获取用户信息，新建聊天框，并放入第一个
      const res = await getUserById({
        id: Number(routeId)
      });
      if (res.data.code === 0 && res.data.data) {
        chatRecords.value?.unshift({
          targetUserVO: res.data.data.userVO,
          targetTeamVO: null,
          chatVO: []
        })
        console.log(chatRecords.value)
        console.log(res.data.data.userVO)
        currentChat.value = chatRecords.value[0];
        setTimeout(() => {
          scrollToBottom();
        }, 100);
      } else {
        message.error("网络出现波动，获取用户信息失败")
        //若有聊天记录，则选择第一个，并滚动到底部
        if (chatRecords.value.length > 0) {
          currentChat.value = chatRecords.value[0];
          setTimeout(() => {
            scrollToBottom();
          }, 100);
        }
      }
    }
  }
  //若有聊天记录，则选择第一个，并滚动到底部
  if (chatRecords.value.length > 0) {
    currentChat.value = chatRecords.value[0];
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  }
}

//初始化websocket
let ws: WebSocket | null = null

//发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !currentChat.value) return

  const msg = {
    fromId: currentUser.value.id,
    toId: currentChat.value.targetUserVO?.id ?? null,
    teamId: currentChat.value.targetTeamVO?.id ?? null,
    text: newMessage.value.trim(),
    chatType: currentChat.value.targetUserVO ? 1 : 2
  }
  console.log("发送消息:" + msg.text)

  ws?.send(JSON.stringify(msg))
  newMessage.value = ''          // 清空输入框
  //将消息塞入聊天记录中
  //构建新聊天记录对象
  const chatVO: ChatVO = {
    ...msg,
    createTime: new Date(),
    isRead: 1
  }
  chatRecords.value.forEach(chatRecord => {
    if ((chatVO.chatType == 1 && chatRecord.targetUserVO?.id == msg.toId) || (chatVO.chatType == 2 && chatRecord.targetTeamVO?.id == msg.teamId)) {
      chatRecord.chatVO.push(chatVO)
      setTimeout(() => {
        scrollToBottom();
      }, 100);
      return
    }
  })
}




// 页面挂载时初始化
onMounted(async () => {
  await fetchChatRecords();
  await InitPage();
  ws = new WebSocket(`ws://localhost:8123/api/chat/${currentUser.value.id}`)
  ws.onopen = () => console.log('ws connected')
  ws.onmessage = (e) => {
    /* 后端回包直接 push 到当前会话，简单示例 */
    const chatVO: ChatVO = JSON.parse(e.data)
    if (!currentChat.value) return

    console.log("收到消息：" + chatVO.text)
    console.log("chatVO的chatType：" + chatVO.chatType)


    /* 如果是当前聊天就把消息追加进去 */
    chatRecords.value.forEach(chatRecord => {
      console.log("chatRecord.targetUserVO?.id：" + chatRecord.targetUserVO?.id)
      if ((chatVO.chatType == 1 && chatRecord.targetUserVO?.id == chatVO.fromId) || (chatVO.chatType == 2 && chatRecord.targetTeamVO?.id == chatVO.teamId)) {
        console.log("chatVO:" + chatVO.text)
        chatRecord.chatVO.push(chatVO)
        setTimeout(() => {
          scrollToBottom();
        }, 100);
        return
      }
    })


    // const sameChat =
    //     (chatVO.chatType === 1 && chatVO.fromId === currentChat.value.targetUserVO?.id) ||
    //     (chatVO.chatType === 2 && chatVO.teamId === currentChat.value.targetTeamVO?.id)
    //
    // if (sameChat) {
    //   currentChat.value.chatVO.unshift(chatVO)
    //   setTimeout(scrollToBottom, 100)
    // }
  }

});
</script>

<template>
  <div id="ChatPage" class="chat-page">

    <!-- 左侧联系人列表 -->
    <div class="chat-contacts">
      <div class="contacts-header">
        <div class="search-bar">
          <SearchOutlined/>
          <input type="text" placeholder="搜索联系人"/>
        </div>
      </div>

      <div class="contacts-list">
        <div
            v-for="contact in chatRecords"
            :key="contact.targetUserVO?.id || contact.targetTeamVO?.id"
            class="contact-item"
            :class="{
                      active: currentChat && (
                        (currentChat.targetUserVO && contact.targetUserVO &&
                         currentChat.targetUserVO.id === contact.targetUserVO.id) ||
                        (currentChat.targetTeamVO && contact.targetTeamVO &&
                         currentChat.targetTeamVO.id === contact.targetTeamVO.id)
                      )
                    }"
            @click="selectChat(contact)"
        >
          <div class="contact-avatar">
            <img
                :src="contact.targetUserVO?.userAvatar || contact.targetTeamVO?.avatar || getDefaultAvatar()"
                alt="Avatar"
                :class="{ 'team-avatar': contact.targetTeamVO }"
            />
          </div>
          <div class="contact-info">
            <div class="contact-name">
              {{ contact.targetUserVO?.username || contact.targetTeamVO?.teamname }}
              <span v-if="contact.targetTeamVO" class="team-icon"><TeamOutlined/></span>
              <span v-else class="user-icon"><UserOutlined/></span>
            </div>
            <div class="contact-last-message">
              {{ contact.chatVO.length > 0 ? contact.chatVO[contact.chatVO.length - 1].text : '暂无消息' }}
            </div>
          </div>
          <div class="contact-time">
            {{ contact.chatVO.length > 0 ? formatTime(contact.chatVO[contact.chatVO.length - 1].createTime) : '' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window" v-if="currentChat">
      <!-- 聊天窗口头部 -->
      <div class="chat-header">
        <div class="chat-title">
          {{ currentChat.targetUserVO?.username || currentChat.targetTeamVO?.teamname }}
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages">

        <div
            v-for="message in currentChat.chatVO"
            :key="message.createTime + message.fromId"
            class="message-wrapper"
            :class="{ 'own-message': message.fromId === currentUser.id }"
        >
          <div v-if="message.fromId !== currentUser.id" class="message-avatar">
            <img
                :src="getContactAvatar(message.fromId)"
                alt="Avatar"
            />
          </div>
          <div class="message-content">
            <div class="message-time">
              {{ formatTime(message.createTime) }}
            </div>
            <div class="message-bubble">
              {{ message.text }}
            </div>
          </div>
          <div v-if="message.fromId === currentUser.id" class="message-avatar">
            <img
                :src="currentUser.userAvatar || getDefaultAvatar()"
                alt="Avatar"
            />
          </div>
        </div>
      </div>

      <!-- 消息输入区域 -->
      <div class="chat-input-area">
        <div class="input-wrapper">
          <input
              v-model="newMessage"
              type="text"
              placeholder="输入消息..."
              @keypress.enter="sendMessage"
          />
          <button class="send-button" @click="sendMessage"
                  :disabled="!newMessage.trim()">
            <SendOutlined/>
          </button>
        </div>
      </div>
    </div>

    <!-- 未选择聊天时的提示 -->
    <div class="chat-empty" v-else>
      <p>请选择一个联系人开始聊天</p>
    </div>
  </div>
</template>

<style scoped>
.chat-page {
  display: flex;
  height: 85vh;
  background-color: #f5f5f5;
}

/* 左侧联系人列表 */
.chat-contacts {
  width: 350px;
  background-color: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.contacts-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 8px 12px;
}

.search-bar input {
  border: none;
  background: transparent;
  outline: none;
  flex: 1;
  margin-left: 8px;
}

.contacts-list {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid #f0f0f0;
}

.contact-item:hover {
  background-color: #f5f5f5;
}

.contact-item.active {
  background-color: #e6f7ff;
}

.contact-avatar img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.contact-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.contact-name {
  display: flex;
  align-items: center;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.contact-last-message {
  font-size: 14px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.contact-time {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.team-icon,
.user-icon {
  margin-left: 8px;
  font-size: 12px;
  color: #1890ff;
}

/* 右侧聊天窗口 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
}

/* 连接状态指示器 */
.connection-status {
  position: fixed;
  top: 10px;
  right: 10px;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.connection-status.connected {
  background-color: #52c41a;
  color: white;
}

.connection-status.connecting {
  background-color: #faad14;
  color: white;
}

.connection-status.disconnected {
  background-color: #f5222d;
  color: white;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: currentColor;
}

.chat-header {
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  padding: 16px 24px;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  max-width: 70%;
  align-self: flex-start;
}

.message-wrapper.own-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-avatar img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-bubble {
  background-color: white;
  padding: 12px 16px;
  border-radius: 18px;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
}

.own-message .message-bubble {
  background-color: #1890ff;
  color: white;
  border-bottom-left-radius: 18px;
  border-bottom-right-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: center;
}

.chat-input-area {
  background-color: white;
  border-top: 1px solid #e8e8e8;
  padding: 16px 24px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 24px;
  padding: 8px 16px;
}

.input-wrapper input {
  flex: 1;
  border: none;
  background: transparent;
  outline: none;
  padding: 8px 0;
  font-size: 14px;
}

.send-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-button:hover {
  background-color: #40a9ff;
}

/* 未选择聊天时的提示 */
.chat-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  color: #999;
  font-size: 16px;
}



.contacts-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.contacts-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.contacts-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.contacts-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

